package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func main() {

	args := os.Args
	if len(args) < 2 {
		fmt.Println("请输入要转码的文件！！！")
		return
	}

	filename := args[1]
	if !strings.Contains(filename, ".kmx") {
		fmt.Println("似乎不是一个kmx文件")
		return
	}
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	file2, err := os.OpenFile(filename +".mp4", os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("创建目标文件失败: " + err.Error())
		return
	}
	defer file.Close()
	defer file2.Close()

	fileInfo, err := os.Stat(filename)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// Whence is the point of reference for offset
	// 0 = Beginning of file
	// 1 = Current position
	// 2 = End of file
	var whence int = 0
	_, err = file.Seek(34, whence)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	bufSize := 100000 //100KB
	var tmpSize int64 = 0
	buf:= make([]byte, bufSize)
	for {
		_, err := file.Read(buf)
		if err == io.EOF {
			break
		}
		tmpSize+=int64(bufSize)

		if err != nil && err != io.EOF {
			fmt.Println(err.Error())
			return
		}

		_ , err = file2.Write(buf)
		if err != nil {
			fmt.Println(err.Error())
			return
		}

		if tmpSize > fileInfo.Size() {
			tmpSize = fileInfo.Size()
		}
		fmt.Printf("已完成:%.2f%%\n", (float64(tmpSize) / float64(fileInfo.Size())) * 100 )
	}
	fmt.Printf("ok.")
}

